package com.gzy.wb.server;

import com.gzy.wb.controller.para.UserCreatePara;
import com.gzy.wb.controller.para.UserUpdatePara;
import com.gzy.wb.core.Page;
import com.gzy.wb.core.R;
import com.gzy.wb.exception.AppException;
import com.gzy.wb.model.MyLog;
import com.gzy.wb.model.User;
import com.gzy.wb.repository.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.beans.FeatureDescriptor;
import java.beans.PropertyDescriptor;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;

@Service
public class UserServer {
    @Autowired
    UserRepository userRepository;

    public List<User> findAll() {
        return userRepository.findAll();
    }

    public User findUserByName(String username) {
        return userRepository.findUserByUsername(username);
    }


    public org.springframework.data.domain.Page<User> findUserByPage(Long page, Long size) {

        Pageable pg = PageRequest.of(page.intValue(), size.intValue());
        org.springframework.data.domain.Page<User> all = userRepository.findAll(pg);

        return all;

//        Page<User> result = new Page<>();
//
//        long offset = size * (page-1);
//
//        List<User> rs = userRepository.pageWhere(offset, size);
//
//        long count = userRepository.count();
//
//
//        long p1 = count / size;
//        long mod = count % size;
//        if (mod != 0){
//            p1+=1;
//        }
//
//        result.setTotalPage(p1);
//        result.setData(rs);
//        result.setCurPage(page);
//        result.setSize(size);
//        result.setTotalSize(count);
//
//        return result;
    }

    public User show(Integer id) {
        var byId = userRepository.findById(id);
        if (byId.isEmpty()) {
            throw new AppException("数据未找到", R.Code.NotFound);
        }
        return byId.get();
    }

    public User create(UserCreatePara para) {

        User byUsername = userRepository.findUserByUsername(para.getUsername());
        if (byUsername != null){
            throw new AppException("已存在该用户",R.Code.ERR);
        }

        User user = new User();

        user.setUsername(para.getUsername());
        user.setPassword(para.getPassword());
        user.setAvatar("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1597317524092&di=5ba502415e012a2689959a631ebea6f0&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201602%2F10%2F20160210200222_4zmt5.jpeg");
//        user
        user.setRole("USER");
        user.setCreateAt(System.currentTimeMillis());

        userRepository.save(user);

        return user;
    }

    public void softDelete(Integer id) {
        Optional<User> byId = userRepository.findById(id);
        if (byId.isEmpty()) {
            throw new AppException("数据未找到", R.Code.NotFound);
        }
        User user = byId.get();
        user.setDeleteAt(System.currentTimeMillis());
        userRepository.save(user);
    }


    /**
     * 获取空 属性名
     * @param source
     * @return
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper wrappedSource = new BeanWrapperImpl(source);
        return Stream.of(wrappedSource.getPropertyDescriptors())
                .map(FeatureDescriptor::getName)
                .filter(propertyName -> wrappedSource.getPropertyValue(propertyName) == null)
                .toArray(String[]::new);
    }

    public User update(Integer id, UserUpdatePara u) {

        Optional<User> byId = userRepository.findById(id);
        if (byId.isEmpty()) {
            throw new AppException("数据未找到", R.Code.NotFound);
        }
        User user = byId.get();



        String[] ignList = getNullPropertyNames(u);
        BeanUtils.copyProperties(u,user,ignList);

//        user.setRole(u.getRole());
//        user.setUsername(u.getUsername());
//        user.setPassword(u.getPassword());
//        user.setAvatar(u.getAvatar());
//        user.setEmail(u.getEmail());

        userRepository.save(user);

        return user;
    }

    public void reenable(Integer id) {
        Optional<User> byId = userRepository.findById(id);
        if (byId.isEmpty()) {
            throw new AppException("数据未找到", R.Code.NotFound);
        }
        User user = byId.get();
        user.setDeleteAt(null);
        userRepository.save(user);
    }
}
